package cn.ynrcb.personnelfile.admin.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.ynrcb.personnelfile.admin.enums.AuditStatusEnum;
import cn.ynrcb.personnelfile.admin.enums.SmsTypeEnum;
import cn.ynrcb.personnelfile.admin.entity.FileEntity;
import cn.ynrcb.personnelfile.admin.service.SmsService;
import cn.ynrcb.personnelfile.admin.vo.SmsVo;
import cn.ynrcb.personnelfile.common.annotation.BusinessLog;
import cn.ynrcb.personnelfile.common.validator.ValidatorUtils;
import cn.ynrcb.personnelfile.common.validator.group.AddGroup;
import cn.ynrcb.personnelfile.common.validator.group.UpdateGroup;
import cn.ynrcb.personnelfile.sysadmin.vo.AuditVo;
import cn.ynrcb.personnelfile.common.utils.PageUtils;
import cn.ynrcb.personnelfile.common.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicResponseParameters;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import cn.ynrcb.personnelfile.admin.entity.RegisterInfoEntity;
import cn.ynrcb.personnelfile.admin.service.RegisterInfoService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * 协会注册信息表
 *
 * @author wujianfan
 * @email fanxipo@qq.com
 * @date 2022-04-01 14:55:58
 */
@Api(value = "整改需求系统系统", tags = {"业务相关=>协会注册信息相关接口"})
@RestController
@RequestMapping("admin/registerinfo")
public class RegisterInfoController {
    @Autowired
    private RegisterInfoService registerInfoService;
    @Value("${uploadFilePath}")
    private String uploadFilePath;
    @Autowired
    private SmsService smsService;

    /**
     * 协会注册信息列表
     */
    @ApiOperation("协会注册信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "关键字", example = "abc", required = false),
            @ApiImplicitParam(name = "auditStatus", value = "审核状态", example = "2", required = false),
            @ApiImplicitParam(name = "page", value = "页码", example = "1", required = false),
            @ApiImplicitParam(name = "limit", value = "条数", example = "12", required = false)
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
                    @DynamicParameter(value = "列表", name = "page中的list", example = "page")
            })
    )
    @GetMapping("/list")
    @RequiresPermissions("admin:registerinfo:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = registerInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 协会注册信息
     */
    @ApiOperation("协会注册信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", example = "1", required = true),
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
                    @DynamicParameter(value = "registerInfo", name = "registerInfo", dataTypeClass = RegisterInfoEntity.class)
            })
    )
    @GetMapping("/info/{id}")
    @RequiresPermissions("admin:registerinfo:info")
    public R info(@PathVariable("id") Long id) {
        RegisterInfoEntity registerInfo = registerInfoService.getById(id);

        //处理附件
        ArrayList<Object> fileList = new ArrayList<>();
        String[] fileArr = registerInfo.getFile().split(",");
        for (String s : fileArr) {
            HashMap<Object, Object> map = new HashMap<>();
            FileEntity byId = registerInfoService.getFileById(s);
            if (ObjectUtil.isNotNull(byId)) {
                map.put("name", byId.getFileName());
                map.put("url", byId.getFilePath());
                map.put("id", byId.getId());
                fileList.add(map);
            }
        }
        registerInfo.setFileList(fileList);

        return R.ok().put("registerInfo", registerInfo);
    }

    /**
     * 审核注册用户
     */
    @ApiOperation("审核注册用户")
    @ApiImplicitParams({
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success")
            })
    )
    @BusinessLog("审核注册用户")
    @PostMapping("/audit")
    @RequiresPermissions("admin:registerinfo:audit")
    public R audit(@RequestBody AuditVo params) {
        ValidatorUtils.validateEntity(params, UpdateGroup.class);
        String[] idArry = params.getIds().split(",");
        Integer num = registerInfoService.auditInfo(idArry, params);
        if (num == idArry.length) return R.ok("审核完成，共" + num + "条数据。");
        else return R.error("审核出错，共" + num + "条数据。");
    }

    /**
     * 驳回注册信息处理（无token验证）
     */
    @ApiOperation("驳回注册信息处理（无token验证）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", example = "1800000000", required = true),
            @ApiImplicitParam(name = "smsCode", value = "短信验证码", example = "874512", required = true),
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
                    @DynamicParameter(value = "注册info", name = "info", dataTypeClass = RegisterInfoEntity.class)
            })
    )
    @BusinessLog("驳回注册信息处理")
    @GetMapping("/nopassinfo")
    public R noPassInfo(String phone, String smsCode) {
        //验证短信验证码
        SmsVo.CheckSmsParm param = new SmsVo.CheckSmsParm();
        param.setPhone(phone);
        param.setSmsCode(smsCode);
        param.setType(SmsTypeEnum.BIND_MOBILE);

        if (!smsService.checkSmsCode(param)) {
            return R.error(2012, "短信验证码不正确或已过期！");
        }

        RegisterInfoEntity info = registerInfoService.getOne(
                new QueryWrapper<RegisterInfoEntity>()
                        .eq("phone", phone)
        );

        //处理附件
        ArrayList<Object> fileList = new ArrayList<>();
        String[] fileArr = info.getFile().split(",");
        for (String s : fileArr) {
            HashMap<Object, Object> map = new HashMap<>();
            FileEntity byId = registerInfoService.getFileById(s);
            if (ObjectUtil.isNotNull(byId)) {
                map.put("name", byId.getFileName());
                map.put("url", byId.getFilePath());
                map.put("id", byId.getId());
                fileList.add(map);
            }
        }
        info.setFileList(fileList);

        if (ObjectUtil.isNotNull(info)) {
            //不为空
            if (info.getAuditStatus() == AuditStatusEnum.AUDIT_NO_PASS.getCode()) {
                return R.ok().put("info", info);
            } else {
                return R.error("该账号不在驳回注册信息处理范围内");
            }
        } else {
            return R.error("该账号尚未注册");
        }

    }

    /**
     * 新增注册信息（无token验证）
     */
    @ApiOperation("新增注册信息（无token验证）")
    @ApiImplicitParams({
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
            })
    )
    @BusinessLog("新增注册信息")
    @PostMapping("/save")
    public R save(@RequestBody RegisterInfoEntity registerInfo) {
        ValidatorUtils.validateEntity(registerInfo, AddGroup.class);
        //验证短信验证码
        SmsVo.CheckSmsParm param = new SmsVo.CheckSmsParm();
        param.setPhone(registerInfo.getPhone());
        param.setSmsCode(registerInfo.getSmsCode());
        param.setType(SmsTypeEnum.BIND_MOBILE);

        if (!smsService.checkSmsCode(param)) {
            return R.error(2012, "短信验证码不正确或已过期！");
        }
        //校验社会信用代码格式
        if (!cn.ynrcb.personnelfile.common.utils.ValidatorUtils.isCredictCode(registerInfo.getCreditCode())) {
            return R.error(2014, "社会信用代码格式错误！");
        }
        if (ObjectUtil.isNotNull(registerInfo.getId())) {
            //id不为空则为更新，是注册驳回用户的提交
            registerInfo.setAuditStatus(2);
            registerInfoService.updateById(registerInfo);
        } else {
            //id为空则为新增，是注册新用户
            registerInfoService.userRegister(registerInfo);

        }
        return R.ok();

    }

    /**
     * 注册文件上传（无token验证）
     *
     * @param file
     * @param req
     * @return
     */
    @ApiOperation("注册文件上传（无token验证）")
    @ApiImplicitParams({
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
            })
    )
    @BusinessLog("注册文件上传")
    @PostMapping("/upload")
    public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        Map<String, Object> resultMap = new HashMap<>();
        // 得到上传时的文件名
        String originName = file.getOriginalFilename();
        String strFormat = simpleDateFormat.format(new Date());
        String realPath = uploadFilePath + strFormat;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // 保存文件对象，加上uuid是为了防止文件重名
        String strNewFileName = UUID.randomUUID().toString().replaceAll("-", "") + originName.substring(originName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, strNewFileName));
            String strUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/" + strFormat + strNewFileName;
            resultMap.put("code", "0");
            resultMap.put("status", "success");
            resultMap.put("url", strUrl);
            resultMap.put("filePath", "/" + strFormat + strNewFileName);
            resultMap.put("fileName", originName);
            FileEntity vo = new FileEntity();
            vo.setId(RandomUtil.randomUUID().replaceAll("-", ""));
            vo.setFileName(originName);
            vo.setFilePath("/" + strFormat + strNewFileName);
            registerInfoService.saveFile(vo.getId(), vo.getFileName(), vo.getFilePath());
            resultMap.put("fileId", vo.getId());
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("status", "error");
            resultMap.put("msg", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 文件真删（无token验证）
     *
     * @param id
     * @return
     */
    @ApiOperation("文件真删（无token验证）")
    @ApiImplicitParams({
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
            })
    )
    @BusinessLog("文件真删")
    @GetMapping("/deleteFile/{id}")
    public R deleteFile(@PathVariable("id") String id) {
        FileEntity entity = registerInfoService.getFileById(id);
        String s = uploadFilePath.substring(0, uploadFilePath.length() - 1) + entity.getFilePath();
        FileUtil.del(new File(s));
        registerInfoService.deleteByFileId(id);
        return R.ok();
    }

    /**
     * 注册信息修改
     */
    @ApiOperation("注册信息修改")
    @ApiImplicitParams({
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
            })
    )
    @BusinessLog("注册信息修改")
    @PostMapping("/update")
    @RequiresPermissions("admin:registerinfo:update")
    public R update(@RequestBody RegisterInfoEntity registerInfo) {
        registerInfoService.updateById(registerInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("admin:registerinfo:delete")
    public R delete(@RequestBody Long[] ids) {
        registerInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 编号是否存在
     *
     * @param coding
     * @return
     */
    @GetMapping("/isHave")
    public R isHave(String coding) {
        RegisterInfoEntity one = registerInfoService.getOne(new QueryWrapper<RegisterInfoEntity>().eq("coding", coding));
        if (ObjectUtil.isNotNull(one)) {
            return R.error();
        }
        return R.ok();
    }

}
